package com.turman.common.db

import android.content.Context
import androidx.room.*
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.google.gson.Gson

//database 抽象类
@Database(entities = [DbUser::class, Book::class], version = 2, exportSchema = true,views = [TempBean::class])
@TypeConverters(value = [DataConverter::class])
abstract class CniaoDatabase:RoomDatabase() {
    abstract val userDao:UserDao?
    abstract val bookDao:BookDao?

    companion object{
        const val DB_NAME = "cniao.db"
        private var instance:CniaoDatabase?=null

        @Synchronized
        fun getInstance(context: Context?):CniaoDatabase? {
            if (instance == null) {
                instance = Room.databaseBuilder(context!!,CniaoDatabase::class.java, DB_NAME)
                    .allowMainThreadQueries()  //这里设置可以在主线程中操作数据库
//                    .addMigrations(migration_2)  //设置数据库版本迁移
                    .fallbackToDestructiveMigration()  //数据库更新时强制删除表和数据重新创建
                    .build()
            }

            return instance
        }

        //数据迁移
        val migration_2:Migration = object : Migration(1,2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                //这里操作数据迁移内容，比如删除插入等等
                database.delete("db_user",null,null)
                database.delete("book",null,null)
            }

        }
    }
}

class DataConverter {
    companion object {
        //workinfo转json
        @JvmStatic
        @TypeConverter
        fun converWorkInfo(workInf:WorkInfo):String {
            return Gson().toJson(workInf)
        }

        @JvmStatic
        @TypeConverter
        fun reConverWorkInfo(workInfoStr:String):WorkInfo {
            return Gson().fromJson(workInfoStr, WorkInfo::class.java)
        }
    }
}